from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import random

# 基本配置

# chrome_options=Options()
# chrome_options.add_argument('--headless')
# chrome_options.add_argument('--no-sandbox')
# chrome_options.add_argument('--no-gpu')
# chrome_options.add_argument('--disable-setuid-sandbox')
# chrome_options.add_argument('--single-process')
# chrome_options.add_argument('--window-size=1920,1080')

USER_AGENT = [
    'Opera/9.80 (Windows NT 6.1; WOW64; U; en) Presto/2.10.229 Version/11.62',
    'Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.9.168 Version/11.52',
    'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0',
    'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:21.0) Gecko/20130331 Firefox/21.0',
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0',
]

# 参数 url 为B站视频的链接
def bil_views(url):
    chrome_options = Options()
    chrome_options.add_argument('--headless')
    chrome_options.add_argument("--mute-audio")
    ua = random.choice(USER_AGENT)
    chrome_options.add_argument('--user-agent=%s' % ua)

    # 代码
    browser = webdriver.Chrome(options=chrome_options)

    # 访问网页
    browser.get(url)
    browser.save_screenshot("1.png")
    time.sleep(16)

    # 根据 id 获取播放按钮
    try:
        path = '//*[@id="bilibiliPlayer"]/div[1]/div[1]/div[10]/div[2]/div[2]/div[1]/div[1]/button[1]'
        browser.find_element_by_xpath(path)
        time.sleep(3)
        print('控件抓取成功1')
    except Exception:
        try:
            path = '//*[@id="bilibiliPlayer"]/div[1]/div[1]/div[9]/div[2]/div[2]/div[1]/div[1]/button[1]'
            browser.find_element_by_xpath(path)
            time.sleep(3)
            print('控件抓取成功2')
        except Exception:
            path = '//*[@id="bilibiliPlayer"]/div[1]/div[1]/div[9]/video'
            browser.find_element_by_xpath(path)
            time.sleep(3)
            print('控件抓取成功3')

    # 2倍速播放
    js_2 = '''document.querySelector('video').playbackRate=2'''
    browser.execute_script(js_2)  # 执行js的方法
    # 播放
    button = browser.find_element_by_id('bilibiliPlayer').click()
    print('播放成功')
    # 睡眠，播放随机一段时间
    view_time = [i for i in range(7, 15)]
    time.sleep(random.choice(view_time))
    # 截图，退出
    browser.save_screenshot("click1.png")
    browser.close()  # 关闭当前页面
    browser.quit()  # 关闭浏览器
    time.sleep(random.choice([37, 38, 39, 30, 31, 32, 33, 34, 27, 28, 29, 20, 11, 22, 43, 14]))


if __name__ == "__main__":
    # 播放100次
    for i in range(100):
        bil_views("https://www.bilibili.com/video/BV19p4y1t7AZ/")
